<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">

        <n-form-item label="原密码" path="oldPassword">
          <n-input placeholder="请输入原密码" type="password" v-model:value="formValue.oldPassword" />
        </n-form-item>

        <n-form-item label="新密码" path="newPassword">
          <n-input placeholder="请输入新密码" type="password" v-model:value="formValue.newPassword" />
        </n-form-item>

        <n-form-item label="重复新密码"  path="repeatPassword">
          <n-input placeholder="请重复新密码" type="password" v-model:value="formValue.repeatPassword"  />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">更换密码</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { FormItemRule, useMessage } from 'naive-ui';
import { changePassword } from '@/api/system/user'

const rules = {
  oldPassword: {
    required: true,
    trigger: ['blur'],
    message: '请输入旧密码'
  },
  newPassword: {
    required: true,
    trigger: ['blur'],
    message: '请输入新密码'
  },
  repeatPassword: {
    required: true,
    trigger: ['blur'],
    validator: (rule: FormItemRule, value: string) => {
      rule;
      return new Promise<void>((resolve, reject) => {
        if (value !== formValue.newPassword) {
          reject(Error('密码不匹配'))
        } else if (value == '') {
          reject(Error('密码不能为空'))
        }
        else {
          resolve()
        }
      })
    }
  },
};
const formRef: any = ref(null);
const message = useMessage();

const formValue = reactive({
  oldPassword: '',
  newPassword: '',
  repeatPassword: ''
});

function formSubmit() {
  formRef.value.validate((errors) => {
    if (!errors) {
      // message.success('验证成功');
      changePassword(formValue).then(
        ()=>{
          message.success('成功!');
        }
      )
    } else {
      message.error('验证失败，请填写完整信息');
    }
  });
}
</script>
